package cn.b.sky.user.service.impl;

import cn.b.sky.user.dao.LoginLogDao;
import cn.b.sky.user.service.LoginLogService;
import cn.b.sky.user.service.model.LoginLog;
import cn.b.sky.user.service.model.condition.LoginLogCondition;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service("loginLogService")
public class LoginLogServiceImpl implements LoginLogService {
  @Resource
  LoginLogDao loginLogDao;

  @Override
  public List<LoginLog> selectOnLineLog(LoginLogCondition loginLogCondition) {
    if (loginLogCondition != null) {
      if(StringUtils.isBlank(loginLogCondition.getOrderField())){
        loginLogCondition.setOrderField("logindatetime");
      }
      return loginLogDao.selectOnLineLog(loginLogCondition);
    } else {
      return null;
    }
  }

  @Override
  public int selectOnLineLogCount(String siteCode) {
    return loginLogDao.selectOnLineLogCount(siteCode);
  }

  @Override
  public List<LoginLog> selectHisLog(LoginLogCondition loginLogCondition) {
    if (loginLogCondition != null) {
      if(StringUtils.isBlank(loginLogCondition.getOrderField())){
        loginLogCondition.setOrderField("logoutdatetime");
      }
      return loginLogDao.selectHisLog(loginLogCondition);
    } else {
      return null;
    }
  }

  @Override
  public int selectHisLogCount(LoginLogCondition loginLogCondition) {
    if (loginLogCondition != null) {
      return loginLogDao.selectHisLogCount(loginLogCondition);
    } else {
      return 0;
    }
  }

  @Override
  public void deleteLog(long id) {
    loginLogDao.deleteLog(id);

  }

  @Override
  public void saveLoginLog(LoginLog log) {
    log.setLoginDateTime(new Date());
    log.setStatus("OK");
    loginLogDao.insertLog(log);
  }

  @Override
  public void modifyLoginLog(String sessionId) {
    LoginLog log = new LoginLog();
    log.setSessionId(sessionId);
    log.setLogoutDateTime(new Date());
    loginLogDao.updateLog(log);
  }

  @Override
  public void modifyLoginOutLogByServerStart() {
    LoginLog log = new LoginLog();
    log.setLogoutDateTime(new Date());
    loginLogDao.updateAllLonginingLog(log);
  }

}
